package com.sikaryofficial.information.service.articlesync;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.google.common.collect.Maps;
import com.sikaryofficial.common.redis.service.RedisService;
import com.sikaryofficial.information.constant.ArticleDataSyncConstant;
import com.sikaryofficial.information.constant.DataSyncOptConstant;
import com.sikaryofficial.information.domain.entity.Article;
import com.sikaryofficial.information.domain.entity.ArticleCategoryEntity;
import com.sikaryofficial.information.domain.entity.ArticleExt;
import com.sikaryofficial.information.domain.entity.Attachment;
import com.sikaryofficial.information.domain.mapping.ArticleCategoryEntityMapping;
import com.sikaryofficial.information.domain.mapping.ArticleMapping;
import com.sikaryofficial.information.domain.mapping.AttachmentMapping;
import com.sikaryofficial.information.message.body.InformationMessage;
import com.sikaryofficial.information.service.IArticleCategoryMappingService;
import com.sikaryofficial.information.service.IArticleExtService;
import com.sikaryofficial.information.service.IArticleService;
import com.sikaryofficial.information.service.IAttachmentService;
import com.sikaryofficial.system.api.model.att.AttachmentResp;
import com.sikaryofficial.system.api.model.infomation.ArticleCategoryDTO;
import com.sikaryofficial.system.api.model.infomation.ArticleCategoryObjVO;
import com.sikaryofficial.system.api.model.infomation.ArticleDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.sikaryofficial.common.core.constant.CacheBusinessConstants.ARTICLE_CATEGORY_LIST_KEY;

/**
 * @author : qinjinyuan
 * @desc : 文章数据同步服务
 * @date : 2023/10/31 19:03
 */
@Slf4j
@Service(value = ArticleDataSyncConstant.ARTICLE + DataSyncStrategy.SUFFIX)
public class ArticleDataSyncService extends AbstractDataSyncService {

    @Autowired
    private IArticleService articleService;
    @Autowired
    private IAttachmentService attachmentService;
    @Autowired
    private IArticleCategoryMappingService categoryMappingService;
    @Autowired
    private IArticleExtService articleExtService;
    @Autowired
    private RedisService redisService;

    /**
     * 数据同步处理
     *
     * @param message
     */
    @Override
    public void processSync(InformationMessage message) {
        /**
         * 同步类型： INSERT | DELETE
         */
        if (DataSyncOptConstant.INSERT.equals(message.getType())) {
            saveSyncData(message.getArticleList());
        } else {
            log.error("ArticleDataSync同步类型错误");
        }
    }

    private void saveSyncData(List<ArticleDTO> articleList) {
        try {
            // 其他数据处理
            processExtData(articleList);
            // 处理文章数据
            List<Article> articles = ArticleMapping.INSTANCE.coverToArticleList(articleList);
            for (Article item : articles) {
                item.setUpdatedTime(Objects.isNull(item.getUpdatedTime()) ? new Date() : item.getUpdatedTime());
                item.setUpdatedBy(0L);
                item.setCreatedBy(Objects.isNull(item.getCreatedBy()) ? 0L : item.getCreatedBy());
            }
            articleService.saveOrUpdateBatch(articles, 2000);
        } catch (Exception e) {
            log.error("updateSyncData error,{}", e);
        }
    }

    /**
     * 处理扩展数据
     *
     * @param articleList
     */
    private void processExtData(List<ArticleDTO> articleList) {
        if (CollUtil.isEmpty(articleList)) {
            return;
        }
        List<Attachment> allAttachments = Lists.newArrayList();
        List<ArticleCategoryEntity> allArticleCategory = Lists.newArrayList();
        List<ArticleExt> articleExtList = Lists.newArrayList();
        // 批量更新逻辑
        try {
            for (ArticleDTO item : articleList) {
                Long articleId = item.getArticleId();
                if (Objects.isNull(articleId)) {
                    continue;
                }
                // 附件数据
                handleAttachments(allAttachments, item);
                // 分类数据及分类映射数据
                handleArticleCategories(allArticleCategory, articleExtList, item, articleId);
                // 删除附件表
                deleteAttachments(articleId, allAttachments);
                // 删除分类映射表
                deleteCategoryMapping(articleId, allArticleCategory);
            }
            // 执行批量保存
            attachmentService.saveBatch(allAttachments, 2000);
            categoryMappingService.saveBatch(allArticleCategory, 2000);
            articleExtService.saveOrUpdateBatch(articleExtList, 2000);
        } catch (Exception e) {
            log.error("ArticleDataSyncService processExtData error,{}", e);
        }
    }

    private void deleteCategoryMapping(Long articleId, List<ArticleCategoryEntity> allArticleCategory) {
        if (CollUtil.isEmpty(allArticleCategory)) {
            return;
        }
        categoryMappingService.update(new LambdaUpdateWrapper<ArticleCategoryEntity>()
                .setSql(" deleted_version = article_category_mapper_id ")
                .set(ArticleCategoryEntity::getUpdatedBy, 0L)
                .set(ArticleCategoryEntity::getUpdatedTime, new Date())
                .eq(ArticleCategoryEntity::getArticleId, articleId)
                .eq(ArticleCategoryEntity::getDeletedVersion, 0L)
        );
    }

    private void deleteAttachments(Long articleId, List<Attachment> allAttachments) {
        if (CollUtil.isEmpty(allAttachments)) {
            return;
        }
        attachmentService.update(new LambdaUpdateWrapper<Attachment>()
                .setSql(" deleted_version = attachment_id ")
                .set(Attachment::getUpdatedBy, 0L)
                .set(Attachment::getUpdatedTime, new Date())
                .eq(Attachment::getObjectId, articleId)
                .eq(Attachment::getDeletedVersion, 0L)
        );
    }

    private void handleAttachments(List<Attachment> allAttachments, ArticleDTO item) {
        List<AttachmentResp> attachmentList = item.getAttachmentList();
        if (CollUtil.isNotEmpty(attachmentList)) {
            for (AttachmentResp attachmentResp : attachmentList) {
                Attachment attachment = AttachmentMapping.INSTANCE.coverToEntity(attachmentResp);
                attachment.setAttachmentId(IdWorker.getId());
                attachment.setCreatedBy(0L);
                attachment.setCreatedTime(new Date());
                allAttachments.add(attachment);
            }
        }
    }

    private void handleArticleCategories(List<ArticleCategoryEntity> allArticleCategory, List<ArticleExt> articleExtList, ArticleDTO item, Long articleId) {
        List<ArticleCategoryObjVO> articleCategoryList = item.getArticleCategoryList();
        if (CollUtil.isEmpty(articleCategoryList)) {
            return;
        }
        Map<Long, String> categoryMap = categoryMap();
        for (ArticleCategoryObjVO categoryObjVO : articleCategoryList) {
            // 额外添加字段
            categoryObjVO.setCover(MapUtils.getObject(categoryMap, categoryObjVO.getArticleCategoryId()));
            // 设值 article_category_mapper_t 表数据
            ArticleCategoryEntity entity = ArticleCategoryEntityMapping.INSTANCE.coverToEntity(categoryObjVO);
            entity.setArticleCategoryMapperId(IdWorker.getId());
            entity.setArticleId(articleId);
            entity.setCreatedBy(0L);
            entity.setCreatedTime(new Date());
            allArticleCategory.add(entity);
        }
        ArticleExt articleExt = new ArticleExt();
        articleExt.setArticleId(articleId);
        articleExt.setArticleCategoryList(articleCategoryList);
        articleExt.setCreatedBy(item.getCreatedBy());
        articleExt.setCreatedTime(new Date());
        articleExt.setCreatedName(item.getCreatedName());
        articleExtList.add(articleExt);
    }

    public Map<Long, String> categoryMap() {
        List<ArticleCategoryDTO> list = redisService.getCacheObject(buildCacheKey());
        if (CollUtil.isEmpty(list)) {
            return Maps.newHashMap();
        }
        return list.stream().filter(item-> CharSequenceUtil.isNotBlank(item.getCover()))
                .collect(Collectors.toMap(ArticleCategoryDTO::getArticleCategoryId, ArticleCategoryDTO::getCover, (k1, k2) -> k1));
    }

    private String buildCacheKey() {
        return ARTICLE_CATEGORY_LIST_KEY;
    }
}
